import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'

Vue.use(VueRouter)
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function(location) {
  return originalPush.call(this, location).catch(err => {})
};

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'Home',
    component: Home,
    children: [{
      path: '/home/searchpopup',
      component: () => import(/* webpackChunkName: "searchpopup" */ '../views/searchPopup.vue')
    }
    ],
    meta:{
      num:0,
      isShowtabBar:true
    }
  },
  {
    path: '/topic',
    name: 'Topic',
    component: () => import('../views/Topic.vue'),
    meta:{
      num:1,
      isShowtabBar:true
    }
  },
  {
    path: '/category',
    name: 'Category',
    component: () => import( '../views/Category.vue'),
    meta:{
      num:2,
      isShowtabBar:true
    }
  },
  {
    path: '/cart',
    name: 'Cart',
    component: () => import('../views/Cart.vue'),
    meta:{
      num:3,
      isShowtabBar:true
    }
  },
  {
    path: '/user',
    name: 'User',
    component: () => import('../views/User.vue'),
    meta:{
      num:4,
      isShowtabBar:true
    }
  },
  {
    path: '/productsDetail',
    name: 'productsDetail',
    component: () => import( '../components/products/productsDetail.vue'),
    meta:{
      isShowtabBar:false
    }
  },
  {
    path: '/channel',
    name: 'Channel',
    component: () => import( '../components/Channel.vue'),
    meta:{
      isShowtabBar:false
    }
  }
  
]

const router = new VueRouter({
  mode:'history',
  base:process.env.BASE_URL,
  routes
})

//导航守卫主要用来通过跳转或取消的方式守卫导航
//路由守卫/路由拦截
// router.beforeEach((to,from,next)=>{ //<br>　　//从cookie中取值并给vux中的token赋值
//   store.commit('setToken',Cookie.get('token')) //<br>　　//如果vux有值就讲登录状态改成1
//   if(store.state.token){
//     store.commit('changIsSignIn',1)
//   } //<br>　//判断是否为true，如果为true就是要登录，去判断token是否存在。存在就执行，不存在就跳转登录页面
//   if(to.meta.requireAuth){
//     if(store.state.token){
//       next()
//     }else{
//       next({path:'/login'})
//     }
//   }else{
//     next()
//   }
// })

router.beforeEach((to,from,next)=>{
  console.log("to",to) //to为一个对象，包含了即将要去的路由的信息

  //点击购物车，如果用户已经登陆了，就直接放行
  if(to.path=="/cart"){
    console.log('已经进入了购物车页面')
    let token=localStorage.getItem('token')
    if(token){
      next()
    }else{
      //这里的toast不能直接用this
      Vue.prototype.$toast('请先登陆');
      setTimeout(()=>{
        next("/user")
      },1000)
    }
    //这里的return只会让next()执行一次
    return
  }
  next()
})
export default router
